package util

import (
	"errors"
	"fmt"
	"math/rand"
	"net"
	"time"

	logger "github.com/sirupsen/logrus"
)

// 获取本机IP地址
func GetLocalIPAddress() (string, error) {
	addresses, err := net.InterfaceAddrs()
	if err != nil {
		logger.Warnf("err:%#v", err)
		return "", err
	}
	for _, value := range addresses {
		if ipNet, ok := value.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
			if ipNet.IP.To4() != nil {
				return ipNet.IP.String(), nil
			}
		}
	}
	return "", errors.New("can't get ip address")
}

// 格式化时间
func Format(date time.Time) string {
	return date.Format("2006-01-02 15:04:05")
}

// 生成随机ID
// TODO 可以考虑使用雪花算法生成
func GenerateId() string {
	suffer := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
	return time.Now().Format("20060102150405") + suffer
}
